package cn.com.coding.app;


import cn.com.coding.common.lang.ResT;
import cn.com.coding.system.domin.ProductImageEntity;
import cn.com.coding.system.service.ProductImageService;
import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Api(tags = "测试模块")
@RestController
public class CatTestController {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Value("${uploadPathImg}")
    private String uploadPathImg;

    @Autowired
    private ProductImageService productImageService;

    @RequestMapping("/test/one")
    public ResT test() {
        //加密后
        String password = bCryptPasswordEncoder.encode("admin");
        System.out.println(password);
        boolean metches = bCryptPasswordEncoder.matches("admin", password);

        System.out.println(metches + "匹配结果");


        return ResT.ok();
    }

    @RequestMapping("/test/hdaoop")
    public ResT hdaoop() {



        return ResT.ok();
    }


    public ResT testPic(@RequestParam("picture") MultipartFile picture) {


        return ResT.ok();
    }

    @PostMapping({"doUpload"})
    @ApiOperation("文件上传(不需要token令牌)")
    @ApiResponses({@io.swagger.annotations.ApiResponse(code = 200, message = "请求成功,返回结果result:{filename 文件名},{base64 base64编码}"), @io.swagger.annotations.ApiResponse(code = 400, message = "请求失败")})
    public ResT doUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null) {
            return ResT.error("文件上传失败");
        }
        // 原文件名称
        String filename = file.getOriginalFilename();

        // 创建临时文件
        File tempFile = File.createTempFile("tem", null);
        file.transferTo(tempFile);
        tempFile.deleteOnExit();

        // 文件输入流
        FileInputStream inputStream = new FileInputStream(tempFile);

        byte[] buffer = new byte[(int) tempFile.length()];
        inputStream.read(buffer);
        inputStream.close();

        // 转换为base64编码格式
        String base64 = new sun.misc.BASE64Encoder().encode(buffer);

        // 上面方法中获得的base64编码中，包含有换行符，统一全部替换掉
        base64 = base64.replaceAll("[\\s*\t\n\r]", "");

        ProductImageEntity goodImageEntity = new ProductImageEntity();
        goodImageEntity.setImgUrl(base64);
        productImageService.save(goodImageEntity);

        return ResT.ok().setData(MapUtil.builder().put("goodImageEntity", goodImageEntity).build());
    }


    /**
     * 上传文件控制器
     *
     * @param file 文件上传类
     * @return ModelAndView
     */
    @RequestMapping("/test/pic")
    public ResT update(@RequestParam("file") MultipartFile file) {


        try {
            if (file != null) {
                String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                // 注意这里需要添加目录信息
                String uploadFileDir = uploadPathImg;
//                GoodImageEntity goodImageEntity = new GoodImageEntity();
//                goodImageEntity.setImgUrl("/static/upload/" + fileName);
//                goodImageEntity.setGoodPid("1");
//                productImageService.save(goodImageEntity);
                // 第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录
                File uploadFileDirFile = new File(uploadFileDir);
                if (!uploadFileDirFile.exists()) {
                    uploadFileDirFile.mkdirs();
                }
                // 把浏览器上传的文件复制到希望的位置
                File targetFile = new File(uploadFileDirFile, fileName);

                file.transferTo(targetFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResT.ok();
    }

    @RequestMapping("/test/pic/{pid}")
    public ResT getPic(@PathVariable("pid") String pid) {

        ProductImageEntity productImageEntity = productImageService.getById(pid);

        return ResT.ok().setData(productImageEntity);
    }

    @RequestMapping("/api/public/docs/README.md")
    public ResT getAbout() throws IOException {

        String readme = "README.md";

        //1.获取通道
        FileInputStream fin = new FileInputStream(readme);
        FileChannel fc = fin.getChannel();

        //2.创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        int length = -1;
        StringBuffer stringBuffer = new StringBuffer();
        //3.将数据从通道读到缓冲区中
        while ((length = fc.read(buffer)) != -1) {
            stringBuffer.append(new String(buffer.array()));
            buffer.clear();
        }
        fin.close();

        return ResT.ok().setData(stringBuffer.toString().trim());
    }

}
